package com.gui;

import com.manage.*;
import com.virtual.Run;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;
import java.util.Vector;

public class ScoreManagementPanel extends JPanel {
    private Run systemManager;
    private JComboBox<ClassRoom> classSelector;
    private JTable scoreTable;
    private DefaultTableModel tableModel;
    private JTextArea statisticsArea;
    
    public ScoreManagementPanel(Run systemManager) {
        this.systemManager = systemManager;
        initializeUI();
        // 初始化后立即更新列表
        updateClassSelector();
        // 如果有班级，选择第一个班级并更新成绩显示
        if (classSelector.getItemCount() > 0) {
            classSelector.setSelectedIndex(0);
            updateScoreDisplay();
        }
    }
    
    private void initializeUI() {
        setLayout(new BorderLayout(10, 10));
        
        // 顶部面板：班级选择和导出按钮
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        classSelector = new JComboBox<>();
        JButton exportButton = new JButton("导出成绩");
        JButton refreshButton = new JButton("刷新数据");
        topPanel.add(new JLabel("选择班级："));
        topPanel.add(classSelector);
        topPanel.add(exportButton);
        topPanel.add(refreshButton);
        
        // 中间面板：成绩表格和统计信息
        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        
        // 成绩表格面板
        JPanel tablePanel = new JPanel(new BorderLayout());
        String[] columnNames = {
            "小组", "学号", "姓名", "答题次数", "正确率", "平均分", "总分", 
            "出勤率", "最近答题", "最近考勤"
        };
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        scoreTable = new JTable(tableModel);
        scoreTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        // 设置列宽
        scoreTable.getColumnModel().getColumn(0).setPreferredWidth(100);
        scoreTable.getColumnModel().getColumn(1).setPreferredWidth(100);
        scoreTable.getColumnModel().getColumn(2).setPreferredWidth(100);
        scoreTable.getColumnModel().getColumn(3).setPreferredWidth(80);
        scoreTable.getColumnModel().getColumn(4).setPreferredWidth(80);
        scoreTable.getColumnModel().getColumn(5).setPreferredWidth(80);
        scoreTable.getColumnModel().getColumn(6).setPreferredWidth(80);
        scoreTable.getColumnModel().getColumn(7).setPreferredWidth(80);
        scoreTable.getColumnModel().getColumn(8).setPreferredWidth(150);
        scoreTable.getColumnModel().getColumn(9).setPreferredWidth(150);
        
        tablePanel.add(new JLabel("学生成绩详情："), BorderLayout.NORTH);
        tablePanel.add(new JScrollPane(scoreTable), BorderLayout.CENTER);
        
        // 统计信息面板
        JPanel statsPanel = new JPanel(new BorderLayout());
        statisticsArea = new JTextArea();
        statisticsArea.setEditable(false);
        statisticsArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
        statisticsArea.setPreferredSize(new Dimension(400, 200));
        statsPanel.add(new JLabel("统计信息："), BorderLayout.NORTH);
        statsPanel.add(new JScrollPane(statisticsArea), BorderLayout.CENTER);
        
        splitPane.setTopComponent(tablePanel);
        splitPane.setBottomComponent(statsPanel);
        splitPane.setDividerLocation(300);
        
        // 添加到主面板
        add(topPanel, BorderLayout.NORTH);
        add(splitPane, BorderLayout.CENTER);
        
        // 添加事件监听
        classSelector.addActionListener(e -> updateScoreDisplay());
        exportButton.addActionListener(e -> exportScores());
        refreshButton.addActionListener(e -> updateScoreDisplay());
    }
    
    private void updateClassSelector() {
        classSelector.removeAllItems();
        for (ClassRoom classRoom : systemManager.getClasses()) {
            classSelector.addItem(classRoom);
        }
    }
    
    private void updateScoreDisplay() {
        ClassRoom selectedClass = (ClassRoom) classSelector.getSelectedItem();
        if (selectedClass == null) return;
        
        // 清空表格
        tableModel.setRowCount(0);
        
        // 更新表格数据
        for (Group group : selectedClass.getGroups()) {
            for (Student student : group.getMembers()) {
                Vector<Object> row = new Vector<>();
                row.add(group.getName());
                row.add(student.getId());
                row.add(student.getName());
                
                // 答题统计
                List<AnswerRecord> answerRecords = student.getAnswerRecords();
                int totalAnswers = answerRecords.size();
                long correctAnswers = answerRecords.stream()
                    .filter(AnswerRecord::isCorrect)
                    .count();
                double totalScore = answerRecords.stream()
                    .mapToDouble(AnswerRecord::getScore)
                    .sum();
                
                // 考勤统计
                List<AttendanceRecord> attendanceRecords = student.getAttendanceRecords();
                long presentCount = attendanceRecords.stream()
                    .filter(AttendanceRecord::isPresent)
                    .count();
                double attendanceRate = attendanceRecords.isEmpty() ? 0 : 
                    (double) presentCount / attendanceRecords.size() * 100;
                
                // 最近记录
                String lastAnswer = answerRecords.isEmpty() ? "无" : 
                    answerRecords.get(answerRecords.size() - 1).getDateTime().toString();
                String lastAttendance = attendanceRecords.isEmpty() ? "无" : 
                    attendanceRecords.get(attendanceRecords.size() - 1).getDateTime().toString();
                
                row.add(totalAnswers);
                row.add(totalAnswers > 0 ? 
                    String.format("%.2f%%", (double)correctAnswers/totalAnswers*100) : "0%");
                row.add(totalAnswers > 0 ? 
                    String.format("%.2f", totalScore/totalAnswers) : "0.00");
                row.add(String.format("%.2f", totalScore));
                row.add(String.format("%.2f%%", attendanceRate));
                row.add(lastAnswer);
                row.add(lastAttendance);
                
                tableModel.addRow(row);
            }
        }
        
        // 更新统计信息
        updateStatistics(selectedClass);
    }
    
    private void updateStatistics(ClassRoom class_) {
        StringBuilder sb = new StringBuilder();
        sb.append("班级统计信息：\n\n");
        
        // 小组统计
        sb.append("【小组成绩统计】\n");
        sb.append(String.format("%-20s%-10s%-10s%-10s\n", 
            "小组名称", "人数", "平均分", "小组得分"));
        sb.append("------------------------------------------------\n");
        for (Group group : class_.getGroups()) {
            double avgScore = group.getMembers().stream()
                .mapToDouble(s -> s.getAnswerRecords().stream()
                    .mapToDouble(AnswerRecord::getScore)
                    .average()
                    .orElse(0.0))
                .average()
                .orElse(0.0);
            
            sb.append(String.format("%-20s%-10d%-10.2f%-10.2f\n",
                group.getName(),
                group.getMembers().size(),
                avgScore,
                group.getScore()));
        }
        
        // 班级整体统计
        sb.append("\n【班级整体统计】\n");
        int totalStudents = class_.getStudents().size();
        int totalAnswers = 0;
        int totalCorrect = 0;
        double totalClassScore = 0;
        int totalAttendance = 0;
        int totalPresent = 0;
        
        for (Student student : class_.getStudents()) {
            List<AnswerRecord> records = student.getAnswerRecords();
            totalAnswers += records.size();
            totalCorrect += records.stream()
                .filter(AnswerRecord::isCorrect)
                .count();
            totalClassScore += records.stream()
                .mapToDouble(AnswerRecord::getScore)
                .sum();
                
            List<AttendanceRecord> attendance = student.getAttendanceRecords();
            totalAttendance += attendance.size();
            totalPresent += attendance.stream()
                .filter(AttendanceRecord::isPresent)
                .count();
        }
        
        sb.append(String.format("总人数：%d\n", totalStudents));
        sb.append(String.format("总答题次数：%d\n", totalAnswers));
        sb.append(String.format("平均正确率：%.2f%%\n", 
            totalAnswers > 0 ? (double)totalCorrect/totalAnswers*100 : 0));
        sb.append(String.format("班级总分：%.2f\n", totalClassScore));
        sb.append(String.format("班级平均分：%.2f\n", 
            totalStudents > 0 ? totalClassScore/totalStudents : 0));
        sb.append(String.format("班级出勤率：%.2f%%\n", 
            totalAttendance > 0 ? (double)totalPresent/totalAttendance*100 : 0));
        
        statisticsArea.setText(sb.toString());
    }
    
    @Override
    public void setVisible(boolean visible) {
        super.setVisible(visible);
        if (visible) {
            updateClassSelector();
            if (classSelector.getItemCount() > 0) {
                classSelector.setSelectedIndex(0);
                updateScoreDisplay();
            } else {
                tableModel.setRowCount(0);
                statisticsArea.setText("");
            }
        }
    }
    
    private void exportScores() {
        ClassRoom selectedClass = (ClassRoom) classSelector.getSelectedItem();
        if (selectedClass != null) {
            systemManager.exportScores(selectedClass);
            JOptionPane.showMessageDialog(this, 
                "成绩导出成功！", 
                "导出成功", 
                JOptionPane.INFORMATION_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(this, 
                "请先选择一个班级！", 
                "提示", 
                JOptionPane.WARNING_MESSAGE);
        }
    }
} 